<script setup lang="ts">
import {
  ClusterOutlined,
  ColumnHeightOutlined,
  DeleteOutlined,
  DownOutlined,
  FormOutlined,
  PlusOutlined,
  ReloadOutlined,
  SettingOutlined,
  UpOutlined,
} from '@ant-design/icons-vue'
import type { MenuProps, TableProps } from 'ant-design-vue'

import { CommTableSize, CommTableSizeItems } from '~/components/comm-table/comm-table-data.ts'
import type { MenuReq, MenuResp } from '~/api/setting/model/menu.ts'
import MenuEditModal from '~/pages/setting/components/menu-edit-modal.vue'
import { MenuTableColumns } from '~/pages/setting/datas/menu-data.ts'
import { enabledMenuStateByIdApi, queryMenuTreeListApi, removeMenuByIdApi } from '~/api/setting/menu.ts'

const message = useMessage()
const router = useRouter()

const tableSize = shallowRef<string[]>(CommTableSize)
const sizeItems = CommTableSizeItems

const columns = MenuTableColumns
const loading = shallowRef(false)

const dataSource = shallowRef<MenuResp[]>([])

const expand = ref(false)
const formQuery = reactive<MenuReq>({
  menuTitleByLike: undefined,
  menuCodeByLike: undefined,
})

const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})

async function init() {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    dataSource.value = await queryMenuTreeListApi()
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

async function onSearch() {
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formQuery.menuTitleByLike = undefined
  formQuery.menuCodeByLike = undefined
  await init()
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]): any[] {
  return columns.value.filter((item) => {
    return value.includes(item.dataIndex)
  })
}

// 备份columns
const filterColumns = ref<any[]>(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */

function handleCheckAllChange(e: any) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked
    ? filterAction(getCheckList.value)
    : filterColumns.value.filter(item =>
      item.dataIndex === 'action')
}

watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

/**
 * 重置事件
 *
 */
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}

/**
 * checkbox点击事件
 *
 */
function handleCheckChange(value: any) {
  filterColumns.value = filterAction(value)
}

const loadingOfSwitch = shallowRef(false)
/**
 * 菜单状态开启或关闭
 */
async function onSwitchChange(item: MenuResp) {
  loadingOfSwitch.value = true
  const menuResp: MenuReq = {
    id: item.id,
  }
  const result = await enabledMenuStateByIdApi(menuResp)
  if (result) {
    loadingOfSwitch.value = false
    await init()
  }
}

/**
 * 删除功能
 *
 * @param item
 */
async function onDeleteMenu(item: MenuResp) {
  const close = message.loading('删除中......')
  try {
    const menuReq: MenuReq = {
      id: item.id,
    }
    const isDel = await removeMenuByIdApi(menuReq)
    if (isDel) {
      await init()
    }
    message.success('删除成功')
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

const openEdit = ref(false)
const optType = ref('create')
const menuResp = ref<MenuResp>({})

function openModalEditMenu(opt: string, item?: MenuResp) {
  openEdit.value = true
  optType.value = opt
  if (opt === 'create') {
    menuResp.value = {}
  } else {
    menuResp.value = item || {}
  }
}

async function onSaveSuccess() {
  openEdit.value = false
  await onSearch()
}

function gotoComponentApiEdit(item: MenuResp) {
  router.push({ path: '/setting/menu-component-api-detail', query: { id: item.id, type: item.type } })
}

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formQuery">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="menuName" label="菜单名称">
              <a-input v-model:value="formQuery.menuTitleByLike" placeholder="请输入菜单名称" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="menuCode" label="菜单编码">
              <a-input v-model:value="formQuery.menuCodeByLike" placeholder="请输入菜单编码" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :span="24" style="text-align: right">
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
              <a-button type="link" @click="expand = !expand">
                {{ expand ? '收起' : '展开' }}
                <UpOutlined v-if="expand" />
                <DownOutlined v-else />
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="查询表格">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="openModalEditMenu('create')">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
          <a-tooltip title="列设置">
            <a-dropdown v-model:open="dropdownVisible" trigger="click">
              <SettingOutlined />
              <template #overlay>
                <a-card>
                  <template #title>
                    <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate" @change="handleCheckAllChange">
                      列选择
                    </a-checkbox>
                  </template>
                  <template #extra>
                    <a-button type="link" @click="handleResetChange">
                      重置
                    </a-button>
                  </template>
                  <a-checkbox-group v-model:value="state.checkList" :options="options" style="display: flex; flex-direction: column;" @change="handleCheckChange" />
                </a-card>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table
        v-if="dataSource && dataSource.length > 0"
        :loading="loading"
        :columns="filterColumns"
        :data-source="dataSource"
        :size="tableSize[0] as TableProps['size']"
        :default-expand-all-rows="true"
        bordered
      >
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'menuTitle'">
            <span class="bold-text">{{ scope?.record?.menuTitle }}</span>
          </template>
          <template v-if="scope?.column?.dataIndex === 'stateId'">
            <a-switch
              :checked="(scope?.record?.stateValue)"
              checked-children="有效"
              un-checked-children="无效"
              :loading="loadingOfSwitch"
              @change="onSwitchChange(scope?.record)"
            />
          </template>

          <template v-if="scope?.column?.dataIndex === 'action'">
            <div>
              <span>
                <a><FormOutlined @click="openModalEditMenu('edit', scope?.record)" /></a>
                <a-divider type="vertical" />
                <a><ClusterOutlined @click="gotoComponentApiEdit(scope?.record)" /></a>
                <a-divider type="vertical" />
                <a-popconfirm
                  v-if="dataSource.length"
                  title="确认删除?"
                  @confirm="onDeleteMenu(scope?.record)"
                >
                  <a><DeleteOutlined /></a>
                </a-popconfirm>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <MenuEditModal
      v-if="openEdit"
      v-model:open="openEdit"
      :opt-type="optType"
      :menu-data="menuResp"
      @on-save-success="onSaveSuccess"
    />

    <!--    <MenuPermissionModal -->
    <!--      v-if="openPermission" -->
    <!--      v-model:open="openPermission" -->
    <!--      :menu-data="menuResp" -->
    <!--      @on-auth-success="onAuthSuccess" -->
    <!--    /> -->
  </page-container>
</template>

<style scoped lang="less">
/* 使用关键字 */
.bold-text {
  font-weight: bold;
}
</style>
